package com.fpt.edu.vn.h2tv.api.listener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.fpt.edu.vn.h2tv.common.AppConfiguration;
public class BookStoreServiceListener implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //parse xml dùng SAX or StAX. recommend dung SAX
        System.out.println();
        File file = new File(sce.getServletContext().getRealPath("/")+"/WEB-INF/classes/appconfig.xml");
        System.out.println(file.getAbsolutePath());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream stream = sce.getServletContext().getResourceAsStream("/WEB-INF/classes/appconfig.xml");
           Document dom= db.parse(stream);
           NodeList element = dom.getElementsByTagName("app");
           if(element!=null&&element.getLength()>0){
               //get first node
               NodeList childs = element.item(0).getChildNodes();
              for(int i = 0;i<childs.getLength();i++){
                  System.out.println("OK CO HANG");
                  Node node = childs.item(i);
                //  System.out.println(node.getNodeName());
                      if(node.getNodeName().equals("ByPassEnalble")){
                          AppConfiguration.isAuthenEnable = Boolean.parseBoolean(node.getTextContent());
                      }else if(node.getNodeName().equals("ByPassKey")){
                          AppConfiguration.authenKey = node.getTextContent();
                      }else if(node.getNodeName().equals("ByPassValue")){
                          AppConfiguration.authenValue = node.getTextContent();
                      }else if(node.getNodeName().equals("InformationURL")){
                          AppConfiguration.informationConfigurationFile = node.getTextContent();
                      }
                      
              }
           }
        } catch (ParserConfigurationException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }catch (SAXException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        } catch (IOException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        
    }

}
